// PlaylistList.js （原bookdata.js改造）
import React, { useState, useEffect } from 'react';
import {Table, Card, Row, Col, Input, Select, Pagination, Space, message} from 'antd';
import axios from 'axios';
  // components/PlaylistDetail.js
import { Button, Modal, Descriptions } from 'antd';

const { Search } = Input;
const { Option } = Select;

const PlaylistList = () => {
  const [playlists, setPlaylists] = useState([]);
  const [filteredPlaylists, setFilteredPlaylists] = useState([]);
  const [currentView, setCurrentView] = useState('table'); // 'table' 或 'card'
  const [searchType, setSearchType] = useState('name');
  const [currentPage, setCurrentPage] = useState(1);
  const pageSize = 8;
  const [collectingStates, setCollectingStates] = useState({});

  // 列定义（表格模式）
  const columns = [
    {
      title: '歌单名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '创建时间',
      dataIndex: 'created_date',
      key: 'created_date',
    },
    {
      title: '类型',
      dataIndex: 'type',
      key: 'type',
    },
    {
      title: '播放量',
      dataIndex: 'play_count',
      key: 'play_count',
      render: count => <span>{count.toLocaleString()}</span>
    },
    {
      title: '收藏量',
      dataIndex: 'favorite_count',
      key: 'favorite_count',
      render: count => <span>{parseInt(count).toLocaleString()}</span>
    },
    {
      title: '分享量',
      dataIndex: 'share_count',
      key: 'share_count'
    },
    {
      title: '评论量',
      dataIndex: 'comment_count',
      key: 'comment_count'
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          {/* 1. 详情按钮 */}
          <PlaylistDetail data={record} />
          {/* 2. 收藏按钮 */}
          <Button
            type={collectingStates[record.name] ? 'primary' : 'default'}
            onClick={() => handleCollect(record.name)}
            loading={collectingStates[record.name] === 'loading'}
          >
            {collectingStates[record.name] ? '已收藏' : '收藏'}
          </Button>
        </Space>
      )
    }
  ];

  // 获取数据
  useEffect(() => {
    axios.get('http://localhost:5000/playlists')
      .then(res => {
        const data = res.data.data.map(item => ({
          ...item,
          favorite_count: parseInt(item.favorite_count) || 0
        }));
        setPlaylists(data);
        setFilteredPlaylists(data);
      });
  }, []);
  // 新增：初始化收藏状态
  useEffect(() => {
      const user = window.localStorage.getItem('loggedUser');
      axios.get('http://localhost:5000/user-collections', { // [!code ++]
        params: { username: user }
      })
      .then(res => {
        const collectedNames = res.data.map(p => p.name);
        const states = {};
        playlists.forEach(p => states[p.name] = collectedNames.includes(p.name));
        setCollectingStates(states);
      });
  }, [playlists]);

  // 处理搜索
  const handleSearch = (value) => {
    const filtered = playlists.filter(playlist => {
      if (searchType === 'name') {
        return playlist.name.toLowerCase().includes(value.toLowerCase());
      }
      if (searchType === 'tags') {
        return playlist.tags.some(tag => tag.toLowerCase().includes(value.toLowerCase()));
      }
      return true;
    });
    setFilteredPlaylists(filtered);
  };

  // 1. 歌单详情组件
  const PlaylistDetail = ({ data }) => {
    const [isModalOpen, setIsModalOpen] = useState(false);

    return (
      <>
        <Button type="primary" onClick={() => setIsModalOpen(true)}>
          详情
        </Button>
        <Modal
          title="歌单详细信息"
          open={isModalOpen}
          onCancel={() => setIsModalOpen(false)}
          footer={null}
        >
          <Descriptions bordered>
            <Descriptions.Item label="歌单名称" span={3}>
              {data.name}
            </Descriptions.Item>
            <Descriptions.Item label="创建时间">{data.created_date}</Descriptions.Item>
            <Descriptions.Item label="播放量" span={3}>
              {data.play_count.toLocaleString()}
            </Descriptions.Item>
            <Descriptions.Item label="收藏量" >{data.favorite_count}</Descriptions.Item>
            <Descriptions.Item label="分享量" span={2}>{data.share_count}</Descriptions.Item>
            <Descriptions.Item label="评论量" >{data.comment_count}</Descriptions.Item>
            <Descriptions.Item label="歌单长度" span={2}>{data.playlist_length}</Descriptions.Item>
            <Descriptions.Item label="标签" span={1}>{data.tags}</Descriptions.Item>
            <Descriptions.Item label="类型" span={1}>{data.type}</Descriptions.Item>
          </Descriptions>
        </Modal>
      </>
    );
  };

  // 新增：收藏操作处理
  const handleCollect = (playlistName) => {
        // 从浏览器存储获取真实用户名（与图书系统一致）
    const username = window.localStorage.getItem('loggedUser');

    // 增加用户登录态校验
    if (!username) {
        message.error('请先登录后再操作');
        return;
    }
    const isCollect = collectingStates[playlistName];

    setCollectingStates(prev => ({ ...prev, [playlistName]: 'loading' }));

    axios.post('http://localhost:5000/collect-playlist', {
      username:username,
      playlist_name: playlistName,
      isCollect
    })
    .then(() => {
      // 更新本地数据
      const updatedPlaylists = playlists.map(p => {
        if (p.name === playlistName) {
          return {
            ...p,
            favorite_count: String(isCollect ?
              parseInt(p.favorite_count) - 1 :
              parseInt(p.favorite_count) + 1
            )
          };
        }
        return p;
      });

      setPlaylists(updatedPlaylists);
      setCollectingStates(prev => ({ ...prev, [playlistName]: !isCollect }));
      message.success(isCollect ? '已取消收藏' : '收藏成功');
    })
    .catch(() => {
      message.error('操作失败');
      setCollectingStates(prev => ({ ...prev, [playlistName]: isCollect }));
    });
  };


  // 分页处理
  const currentData = filteredPlaylists.slice(
    (currentPage - 1) * pageSize,
    currentPage * pageSize
  );

  return (
    <div className="content-container">
      {/* 搜索和筛选栏（保持原导航结构） */}
      <div className="search-bar">
        <Select
          defaultValue="name"
          style={{ width: 120 }}
          onChange={val => setSearchType(val)}
        >
          <Option value="name">名称</Option>
          <Option value="tags">标签</Option>
        </Select>
        <Search
          placeholder="输入搜索关键词"
          allowClear
          enterButton="搜索"
          onSearch={handleSearch}
          style={{ width: 300 }}
        />
        {/*<Select*/}
        {/*  defaultValue="table"*/}
        {/*  style={{ width: 120, marginLeft: 16 }}*/}
        {/*  onChange={val => setCurrentView(val)}*/}
        {/*>*/}
        {/*  <Option value="table">表格模式</Option>*/}
        {/*  <Option value="card">卡片模式</Option>*/}
        {/*</Select>*/}
      </div>

      {/* 内容展示区域 */}
      {currentView === 'card' ? (
        <Row gutter={[16, 16]} style={{ marginTop: 20 }}>
          {currentData.map(playlist => (
            <Col key={playlist.name} xs={24} sm={12} md={8} lg={6}>
              <Card
                hoverable

              >
                <Card.Meta
                  title={playlist.name}
                  description={
                    <>
                      <p>类型: {playlist.type}</p>
                      <p>🔥 热度: {(playlist.play_count * 0.5 + playlist.favorite_count * 0.3).toFixed(0)}</p>
                    </>
                  }
                />
              </Card>
            </Col>
          ))}
        </Row>
      ) : (
        <Table
          dataSource={currentData}
          columns={columns}
          rowKey="name"
          pagination={false}
          style={{ marginTop: 20 }}
        />
      )}

      {/* 分页器（保持原样式） */}
      <Pagination
        current={currentPage}
        pageSize={pageSize}
        total={filteredPlaylists.length}
        onChange={page => setCurrentPage(page)}
        showQuickJumper={{
          goToText: '跳转至',  // 修改跳转按钮文字
          page: '页',         // 修改页码单位
            // 可选：自定义输入框提示
          placeholder: '输入页码'
        }}
        style={{ marginTop: 20, textAlign: 'center' }}
      />
    </div>
  );
};

export default PlaylistList;



